package com._9xcloud.leaverequest.service;

import com._9xcloud.leaverequest.domain.Course;
import com._9xcloud.leaverequest.domain.Lesson;
import com._9xcloud.leaverequest.exception.NotFoundException;
import com._9xcloud.leaverequest.repository.LessonRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.Set;

/**
 * Created by Administrator on 2015/5/28.
 */
@Repository
@Transactional
public class LessonServiceImpl implements LessonService {
    @Autowired
    private CourseService courseService;
    @Autowired
    private LessonRepository lessonRepository;

    @Transactional(readOnly = true)
    public Lesson getById(int lessonId) {
        Lesson lesson = lessonRepository.findOne(lessonId);
        if (lesson == null) {
            throw new NotFoundException("Could not find the lesson");
        }
        return lesson;
    }

    @Transactional(readOnly = true)
    public Set<Lesson> getByCourseId(int courseId) {
        Course course = courseService.getById(courseId);
        if (course == null) {
            throw new NotFoundException("Could not find the course");
        }
        return course.getLessons();
    }

    public void removeAll() {
        lessonRepository.deleteAll();
        lessonRepository.flush();
    }
}
